import React, { PureComponent } from 'react';
import { Modal, Form, Select, Input, Upload, message, Icon, Button, Row, Col } from 'antd';
import { connect } from 'dva';
import styles from '../../../components/common/PateoTable/TableList.less';
import { getToken } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common'

const styleRequired = {
  display: 'inline-block',
  marginRight: '4px',
  content: '*',
  fontFamily: 'SimSun',
  lineHeight: '1',
  fontSize: '14px',
  color: '#f5222d',
};
const FormItem = Form.Item;
const { Option } = Select;
@connect(state => ({
  extendForm: state.extendForm,
  qualityTest: state.qualityTest,
  vehicle: state.vehicle,
}))
// @Form.create()
export default class GroupActiveModal extends PureComponent {
  state = {
    icon: null,
    vinList: '',
    previewVisible: false,
    previewImage: '',
    fileList: [],
    vinFileList: [],
    data: [],
    buttonLoading: false,
    urlVisible: {},
    fullFaceUrlList: [],
    backViewUrlList: [],
    businessLicenseUrlList: [],
    count: 0,
    personName:'',
    phoneNumber:'',
  };

  componentDidMount() {
    this.props.onRef(this);
    this.props.dispatch({
      type: 'qualityTest/options',
      payload: { url: '/groupManagement/getOption'},
    });
  }
  componentWillReceiveProps() {
  }
  getLabel = (lable) => <span><span style={styleRequired}>* </span>{lable}</span>;
  setIcon = (urls) => {
    this.setState({
      icon: urls,
    });
  };
  ok = (e) => {
    // e.preventDefault();
    const { form, handleClose, dispatch, page, formValues, qualityUserMap } = this.props;
    const { qualityTest: { options }  } = this.props; // 集团编码关系
    this.refs.form.validateFields().then(((fieldsValue)=>{
      console.log('values', fieldsValue)
      if(this.state.vinList.length < 0)
    {
      message.error("解析vin列表为空");
      return;
    }
    this.setState({
      buttonLoading: true,
    });
    // 进行验证码校验
    dispatch({
      type: 'vehicle/checkVerifCode',
      payload: {
        phone: fieldsValue.phoneNumber,
        code: fieldsValue.captcha,
      },
      callback: (data) => {
        if (data.code !== '0') {
          message.error(data.description);
          this.setState({
            icon: null,
            fileList: [],
            vinFileList: [],
            vinList: '',
            buttonLoading: false,
            fullFaceUrlList: [],
            backViewUrlList: [],
            businessLicenseUrlList: [],
            personName:'',
            phoneNumber:'',
          });
          this.refs.form.resetFields();
          handleClose();
          this.props.dispatch({
            type: 'vehicle/fetch',
            payload: {
              page: 0,
              size: 10,
            }})
        }
      }
    });
    const obj = fieldsValue;
    /**
     *activateType
     *groupName
     * certName
     * phoneNumber
     * this.state.icon    图片
     * this.state.vinList  vin列表
     * backViewUrl
     * billUrl
     * fullFaceUrl
     * businessLicenseUrl
     */
    const option = options.filter(item => item.value === obj.groupCode);
    obj.groupName=option[0].label;
    obj.billUrl=this.state.fileList[0]?.response.data.fileUrl || '';
    obj.vin=this.state.vinFileList[0].response.url || ''; // vin.excel
    obj.data = this.state.vinList; // 提交后台进行处理，vin的集合
    obj.fullFaceUrl=this.state.fullFaceUrlList[0]?.response.data.fileUrl || '';
    obj.backViewUrl=this.state.backViewUrlList[0]?.response.data.fileUrl || '';
    obj.businessLicenseUrl=this.state.businessLicenseUrlList[0]?.response?.data.fileUrl || '';
    dispatch({
      type: 'extendForm/add',
      payload: { url: '/groupManagement/groupSave', ...obj },
      callback: (response) => {
        if (response) {
          response.code === '0' ? message.success('企业集团批量激活申请上传成功') : message.error(response.description);
          this.setState({
            icon: null,
            fileList: [],
            vinFileList: [],
            vinList: '',
            buttonLoading: false,
            fullFaceUrlList: [],
            backViewUrlList: [],
            businessLicenseUrlList: [],
            personName:'',
            phoneNumber:'',
          });
          this.refs.form.resetFields();
          handleClose();
        }
        this.props.dispatch({
          type: 'vehicle/fetch',
          payload: {
            page: 0,
            size: 10,
          }})
      },
    });
  }))
  };
  // 发送验证码
  onGetCaptcha = () => {
    const phone=this.state.phoneNumber;
     this.props.dispatch({
            type: 'qualityTest/fetch',
            payload: { url:'/vehicle/getverifcode',phoneNumber: phone},
            callback: (response) => {
              if (response.code === '0') {
                message.success('发送成功');
                this.state.verif = true;
                let count = 60;
                this.interval = setInterval(() => {
                  count -= 1;
                  this.setState({count});
                  if (count === 0) {
                    clearInterval(this.interval);
                  }
                }, 1000);
              } else {
                message.error(response.description);
              }
            },
          });
  };
  checkFullFaceUrl = (rule, value, callback) => {
    const { fullFaceUrlList } = this.state;
    if (fullFaceUrlList.length === 0) {
      callback('请上传身份证正面照');
      return;
    }
    callback();
  };
  checkBackViewUrl = (rule, value, callback) => {
    const { backViewUrlList } = this.state;
    if (backViewUrlList.length === 0) {
      callback('请上传身份证背面照');
      return;
    }
    callback();
  };
  checkBusinessLicenseUrl = (rule, value, callback) => {
    const { businessLicenseUrlList } = this.state;
    if (businessLicenseUrlList.length === 0) {
      callback('请上传营业执照');
      return;
    }
    callback();
  };
  checkBillUrl = (rule, value, callback) => {
    const { fileList } = this.state;
    if (fileList.length === 0) {
      callback('请上传发票照片压缩包');
      return;
    }
    callback();
  };
  checkVinFile = (rule, value, callback) => {
    if (!this.state.vinList) {
      if (value && value.file && value.file.response && value.file.response.error !== 0) {
        callback(value.file.response.message);
        return;
      }
      callback('请上传文件');
      return;
    }
    callback();
  };
  checkCaptcha = (rule, value, callback) => {
    const { codeVisible } = this.props;
    if (!value) {
      callback('请输入验证码!');
      return;
    }
    callback();
  };
  close = () => {
    const { handleClose } = this.props;
    this.setState({
      icon: null,
      fileList: [],
      vinFileList: [],
      vinList: '',
      fullFaceUrlList: [],
      backViewUrlList: [],
      businessLicenseUrlList: [],
      buttonLoading: false,
      urlVisible: {},
      personName:'',
      phoneNumber: '',
    });
    this.refs.form.resetFields();
    this.refs.form.setFieldsValue({ certName: '', phoneNumber: ''});
    handleClose();
  };
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleChange = (info) => {
    let tempFileList = info.fileList;
    tempFileList = tempFileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }

    this.setState({ fileList: tempFileList });
  };

  handleBatchChange = (info) => {
    console.log('info', info);
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
      this.setState({
        vinList: info.file.response.list,
      });
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (info.file.status === 'done' && info.file.response && info.file.status !== 0) {
      message.error(info.file.response.message);
    } else if (info.file.status === 'removed') {
      this.setState({
        vinList: '',
      });
      const obj = info;
      obj.file = '';
    }
    this.setState({ vinFileList: fileList });
  };
  handleFullFaceUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        fullFaceUrlList: [],
      });
      return;
    }
    this.setState({ fullFaceUrlList: fileList });
  };
  handleBackViewUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        backViewUrlList: [],
      });
      return;
    }
    this.setState({ backViewUrlList: fileList });
  };
  handleBusinessLicenseUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        businessLicenseUrlList: [],
      });
      return;
    }
    this.setState({ businessLicenseUrlList: fileList });
  }
  changeGroup = (value) => {
    const { qualityTest: { options }  } = this.props; // 集团编码关系
    const option = options.filter(item => item.value === value);
    if(option.length>0)
    this.setState({ personName: option[0].personName, phoneNumber: option[0].phoneNumber})
    this.refs.form.setFieldsValue({ certName: option[0].personName, phoneNumber: option[0].phoneNumber});
  };
  beforeUpload = (file) => {
    if (file.type === 'image/jpeg' || file.type === 'image/png') {
      if (file.size / 1024 / 1024 > 5) {
        message.error('图片大小不能大于5MB!');
        return false;
      }
      return true;
    } else {
      message.error('请上传JPG或PNG格式图片！');
      return false;
    }
  };
  renderSimpleForm() {
    const { groupActiveFileUrl, codeVisible } = this.props;
    const { qualityTest: { options }  } = this.props; // 集团编码关系
    const GroupOption = (options || []).map(d =>
      <Option key={d.value}>{d.label}</Option>);
    const { previewVisible, previewImage, fileList,
      vinFileList, buttonLoading, count } = this.state;
    const domain = window.g.url;
    const url = '/common/upload/img';
    const fileurl = '/common/upload/all';
    const filestr = `${domain}${fileurl}`;
    const fileprops = {
      action: filestr,
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders() },
      onChange: this.handleChange,
      multiple: false,
    };
    const str = `${domain}${url}`;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const urlbatch = '/common/uploadCheckVin2';
    const strbatch = `${domain}${urlbatch}`;
    const props = {
      action: strbatch,
      onChange: this.handleBatchChange,
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders() },
      multiple: false,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: true },
    };
    const { groupActiveVisible } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };
    return (
      <div>
        <Modal
          title="集团企业批量激活"
          width={600}
          visible={groupActiveVisible}
          onCancel={this.close}
          footer={[
            <Button key="back" size="default" onClick={this.close}>
              取消
            </Button>,
            <Button loading={buttonLoading} key="save" type="primary" size="default" onClick={() => this.refs.form.submit()}>
              保存
            </Button>,
          ]}
        >
          <Form ref="form" onFinish={this.ok}>
            <FormItem
              {...formItemLayout}
              label="激活类型"
              name="activateType"
              rules={[
                { required: true, message: '请选择车辆激活类型' },
              ]}
              initialValue="7"
            >
              <Select placeholder="请选择车辆激活类型"  disabled>
                <Option value='7' >团购车</Option>
              </Select>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="集团名称"
              name="groupCode"
              rules={[
                { required: true, message: '请选择集团名称' },
              ]}
            >
              <Select placeholder="请选择集团名称" onChange={this.changeGroup} getPopupContainer={triggerNode => triggerNode.parentNode}>
                { GroupOption }
              </Select>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="申报人姓名（法人)"
              name="certName"
              rules={[
                { required: true, message: '请填写申报人姓名',whitespace: true },
              ]}
              initialValue={this.state.personName}
            >
              <Input maxLength="6" placeholder="请填写申报人姓名" disabled/>
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="电话号码"
                name="phoneNumber"
                rules={[{ required: true, message: '电话号码有误', whitespace: true, pattern: /^1[0-9][0-9]\d{8}$/ }]}
                initialValue={this.state.phoneNumber}
              >
                <Input disabled placeholder="请填写电话号码" />
              </FormItem>
            <FormItem
                label={this.getLabel('验证码')}
                style={codeVisible}
                {...formItemLayout}
                name="captcha"
                rules={[{ validator: this.checkCaptcha }]}
              >
                <Row gutter={24}>
                  {/* <Col span={24}> */}
                    <Col span={15}>
                      <Input
                        placeholder="请填写验证码"
                        //onChange={e => this.setState({ captcha: e.target.value })}
                        //onPressEnter={this.checkedPhone}
                      />
                    </Col>
                    <Col span={8} push={1}>
                      <Button
                        type="primary"
                        disabled={count}
                        onClick={this.onGetCaptcha}
                      >
                        { count ? `${count} s` : '获取验证码' }
                      </Button>
                    </Col>
                  {/* </Col> */}
                </Row>
              </FormItem>
            <Row  gutter={24}>
              <Col lg={7} md={12} sm={24} offset={3}> 
                <FormItem
                  labelCol={{span: 24}}
                  label={'身份证正面照'}
                  name="fullFaceUrl"
                  // rules={[{ validator: this.checkFullFaceUrl }]}
                >
                  <Upload
                    action={str}
                    headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                    accept=".png, .gif, .jpeg, .jpg, .bmp"
                    listType="picture-card"
                    fileList={this.state.fullFaceUrlList}
                    onPreview={this.handlePreview}
                    onChange={this.handleFullFaceUrlChange}
                    beforeUpload={this.beforeUpload}
                  >
                    {this.state.fullFaceUrlList.length >= 1 ? null : uploadButton}
                  </Upload>
                </FormItem>
              </Col>
              <Col lg={7} md={12} sm={24}>
                <FormItem
                 labelCol={{span: 24}}
                  label={'身份证背面照'}
                  name="backViewUrl"
                  // rules={[{ validator: this.checkBackViewUrl }]}
                >
                  <Upload
                    action={str}
                    headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                    accept=".png, .gif, .jpeg, .jpg, .bmp"
                    listType="picture-card"
                    fileList={this.state.backViewUrlList}
                    onPreview={this.handlePreview}
                    onChange={this.handleBackViewUrlChange}
                    beforeUpload={this.beforeUpload}
                  >
                    {this.state.backViewUrlList.length >= 1 ? null : uploadButton}
                  </Upload>
                </FormItem>
              </Col>
              <Col lg={7} md={12} sm={24}>
                <FormItem
                 labelCol={{span: 24}}
                  label={'营业执照'}
                  name="businessLicenseUrl"
                  // rules={[{ validator: this.checkBusinessLicenseUrl }]}
                >
                  <Upload
                    action={str}
                    headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                    accept=".png, .gif, .jpeg, .jpg, .bmp"
                    listType="picture-card"
                    fileList={this.state.businessLicenseUrlList}
                    onPreview={this.handlePreview}
                    onChange={this.handleBusinessLicenseUrlChange}
                    beforeUpload={this.beforeUpload}
                  >
                    {this.state.businessLicenseUrlList.length >= 1 ? null : uploadButton}
                  </Upload>
                </FormItem>
              </Col>
            </Row>
            <FormItem
              {...formItemLayout}
              label={'发票照片压缩包'}
              name="billUrl"
              // rules={[{ validator: this.checkBillUrl }]}
            >
              <Upload
                {...fileprops}
                fileList={fileList}
                accept=".7z, .rar, .zip"
              >{
                this.state.fileList.length === 0 ? (
                  <Button>
                    <Icon type="upload"/>上传
                  </Button>
                ) : null
              }
              </Upload>
            </FormItem>
            <FormItem
              {...formItemLayout}
              style={{ marginBottom: '12px' }}
              label={this.getLabel('车辆列表(VIN)')}
              name="listVin"
              rules={[{ validator: this.checkVinFile }]}
            >
              <Upload {...props} fileList={vinFileList}>{
                this.state.vinFileList.length === 0 ? (
                  <Button>
                    <Icon type="upload"/>上传文件
                  </Button>
                ) : null
              }
              </Upload>
            </FormItem>
            <Row>
              <Col md={7} sm={24} />
              <Col md={7} sm={24}>
                {
                  groupActiveFileUrl === '' ?
                    <a disabled title="点击下载模板文件" >暂无模板下载</a>
                    :
                    <a href={groupActiveFileUrl} title="点击下载模板文件" >模板文件下载</a>}
              </Col>
            </Row>
          </Form>
        </Modal>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }


  renderForm() {
    return this.renderSimpleForm();
  }
  render() {
    return (
      <div className={styles.tableListForm}>
        {this.renderForm()}
      </div>
    );
  }
}
